<template>
  <div class="center">
    <div class="header_search " v-if="searchShow">
      <el-form size="mini">
        <div class="flex flex-wrap">
          <el-form-item label="用户名" class="searchI" label-width="120px">
            <el-input size="mini" v-model="listQuery.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="手机号" class="searchI" label-width="120px">
            <el-input size="mini" v-model="listQuery.mobile" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item label="所属管理组编号" class="searchI" label-width="120px">
            <el-select v-model="listQuery.gId" placeholder="请选择所属管理组" size="mini" style="width:163px">
              <el-option v-for="item in authMenu" :key="item.id" :label="item.title" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="vip等级编号" class="searchI" label-width="120px">
            <el-select v-model="listQuery.vId" placeholder="请选择vip等级" size="mini" style="width:163px">
              <el-option v-for="item in vipMenu" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="searchI" label-width="120px">
            <div class="flex felx_align">
              <el-button size="mini" type="primary" @click="getqueryAdmin()">提交</el-button>
              <el-button size="mini" @click="restParams">重置</el-button>
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button icon="el-icon-refresh" type="primary" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="dialogFormVisible = true">添加</el-button>
        <el-button size="mini" type="primary" @click="getexportAuthAdmin">导出用户信息</el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="用户名" value="1"></el-option>
              <el-option label="手机号" value="2"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <el-button size="mini" style="margin:0 8px" type="primary" icon="iconfont iconshaixuan" @click="searchShows"></el-button>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- table -->
    <el-table stripe style="width: 100%" :data="browserTable" :key="key" border fit highlight-current-row ref="tableDataRef" @sort-change="tableSortCge">
      <el-table-column v-if="colData[0].istrue" min-width="130" align="center" prop="username" label="用户名"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="130" align="center" prop="mobile" label="手机号"></el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="130" align="center" prop="realname" label="昵称"></el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="130" align="center" prop="title" label="所属组别"></el-table-column>
      <el-table-column v-if="colData[4].istrue" min-width="150" align="center" prop="email" label="Email"></el-table-column>
      <el-table-column v-if="colData[5].istrue" min-width="80" align="center" prop="name" label="VIP等级"></el-table-column>
      <el-table-column v-if="colData[6].istrue" min-width="120" align="center" prop="fUsername" label="关联账号">
        <template slot-scope="scope">{{scope.row.fUsername != null ? scope.row.fUsername : '无'}}</template>
      </el-table-column>
      <el-table-column v-if="colData[7].istrue" min-width="130" align="center" prop="snCount" label="采购设备数量"></el-table-column>
      <el-table-column v-if="colData[8].istrue" min-width="100" align="center" prop="status" label="用户状态" sortable="custom">
        <template slot-scope="scope">
          <div class="state" :class="scope.row.status == 1 ? 'on_line' : 'off_line'">
            <i class="iconfont icon-dian1"></i>
            <span>{{scope.row.status == 1 ? '启用' : '禁用'}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[9].istrue" min-width="140" align="center" prop="create_time" label="注册时间" sortable="custom">
        <template slot-scope="scope">{{scope.row.create_time | newDate}}</template>
      </el-table-column>
      <el-table-column v-if="colData[10].istrue" min-width="140" align="center" prop="last_login" label="最后登录" sortable="custom">
        <!-- <template slot-scope="scope">{{scope.row.last_login| newDate}}</template> -->
        <template slot-scope="scope">{{scope.row.last_login == 0 ? '未登录' : scope.row.last_login | newDate}}</template>
      </el-table-column>
      <el-table-column min-width="220" align="center" prop="log" label="操作">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="getqueryIdAuthAdmin(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="primary" @click="getenableAuthAdmin(scope.row)">控制</el-button>
            <el-button size="mini" @click="getdeleteAuthAdmin(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <!-- 隐藏 -->
    <!-- 添加dialog表单 -->
    <div>
      <el-dialog title="添加" :visible.sync="dialogFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false">
        <el-form :model="addForm" ref="ruleForm" :rules="rules">
          <el-form-item label="所属组别:" label-width="120px" prop="title">
            <el-select v-model="addForm.title" placeholder="没有选中任何项" class="add_select">
              <el-option v-for="(item,index) in authMenu" :key="index" :label="item.title" :value="item.title"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户名:" label-width="120px" prop="username">
            <el-input v-model="addForm.username" class="add_select" placeholder="请输入您的账号"></el-input>
          </el-form-item>
          <el-form-item label="密码:" label-width="120px" prop="password">
            <el-input ref="redactPassword" v-model="addForm.password" class="add_select" placeholder="请输入您的密码" maxlength="30" :key="redactType" :type="redactType"></el-input>
            <span class="show-pwd" @click="redactshowPwd">
              <svg-icon :icon-class="redactType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
          <el-form-item label="手机号:" label-width="120px" prop="mobile">
            <el-input v-model="addForm.mobile" class="add_select" placeholder="请确认您的手机号码" maxlength="30"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false" size="mini" round>取 消</el-button>
          <el-button type="primary" @click="getsonRegister('ruleForm')" size="mini" round>确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑dialog表单 -->
      <el-dialog title="编辑" :visible.sync="redactFormVisible" @close="redactFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
        <el-form :model="redactForm" :rules="redactRules" ref="redactRuleForm">
          <el-form-item label="所属组别:" label-width="100px" prop="auth_group_id">
            <el-select v-model="redactForm.auth_group_id" placeholder="没有选中任何项" class="add_select">
              <el-option v-for="(item,index) in authMenu" :key="index" :label="item.title" :value="item.title"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户名:" label-width="100px" prop="username">
            <el-input v-model="redactForm.username" class="add_select" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="Email:" label-width="100px" prop="email">
            <el-input v-model="redactForm.email" class="add_select" placeholder="请输入Email" maxlength="30"></el-input>
          </el-form-item>
          <el-form-item label="昵称:" label-width="100px" prop="realname">
            <el-input v-model="redactForm.realname" class="add_select" placeholder="请输入昵称" maxlength="30"></el-input>
          </el-form-item>
          <el-form-item label="VIP等级:" label-width="100px" prop="vip_id">
            <el-select v-model="redactForm.vip_id" placeholder="没有选中任何项" class="add_select">
              <el-option v-for="(item,index1) in vipMenu" :key="index1" :label="item.name" :value="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="内容授权套餐:" label-width="120px" prop="platter_id" v-permission="['超级管理员']">
            <el-select v-model="redactForm.platter_id" placeholder="请选择" multiple collapse-tags>
              <el-option
                v-for="item in platterOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="辅助用户名:" label-width="100px" prop="assist_id">
            <el-input v-model="redactForm.assist_id" class="add_select" placeholder="请输入辅助用户名" maxlength="30"></el-input>
          </el-form-item>
          <el-form-item label="手机号码:" label-width="100px" prop="mobile">
            <el-input v-model="redactForm.mobile" name="mobile" readonly onfocus="this.removeAttribute('readonly')" autocomplete="off" class="add_select" placeholder="请输入手机号码" maxlength="30" />
          </el-form-item>
          <el-form-item label="密码:" label-width="100px" prop="password">
            <el-input ref="redactPassword" v-model="redactForm.password" class="add_select" placeholder="请输入密码" maxlength="30" :key="redactType" :type="redactType"></el-input>
            <span class="show-pwd" @click="redactshowPwd">
              <svg-icon :icon-class="redactType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="redactFormVisible = false" size="mini" round>取 消</el-button>
          <el-button type="primary" @click="updateAuthAdmin('redactRuleForm')" size="mini" round>确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 删除弹窗 -->
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import deleteDialog from "@/components/deleteDialog";
import { queryAdmin, sonRegister, queryVipName, queryAuthGroup, queryIdAuthAdmin, updateAuthAdmin, enableAuthAdmin, deleteAuthAdmin, exportAuthAdmin } from "@/api/infos.js";
import {getPlatter} from "@/api/launcherMade";
import permission from "@/directive/permission";

export default {
  components: { dynamicTable, deleteDialog },
  directives: {permission},

  data() {
    var phoneReg = 11 && /^((13|14|15|17|18|19)[0-9]{1}\d{8})$/
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('号码不能为空!!'))
      }
      if (!phoneReg.test(value)) {
        callback(new Error('手机号码有误'))
      } else {
        callback()
      }
    };
    var validation = (value) => {
      let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/g
      let mat = value.match(cnReg)
      let length
      if (mat) {
        length = (mat.length + (value.length - mat.length) * 0.5)
        return length
      } else {
        return value.length * 0.5
      }
    }
    var validateUsername = (rule, value, callback) => {
      let leng = validation(value)
      if (leng < 2) {
        return callback(new Error('中文最少两位字符，英文最少4位字符'))
      } else {
        callback()
      }
    }
    return {
      changeType: "password",
      checkboxVal: ["用户名", "手机号", "昵称", "所属组别", "Email", "VIP等级", "关联账号", "采购设备数量", "用户状态", "注册时间", "最后登录"],
      key: 1,
      colData: [], //动态控制table
      //归属table
      browserTable: [],
      total: 0,
      searchTable: "",
      select: "", //搜索条件
      //添加按钮控制
      dialogFormVisible: false,
      //浏览器专题id
      subjectId: 0,
      //添加表单
      addForm: { username: "", password: "", mobile: "", title: "" },
      rules: {
        username: [{ validator: validateUsername, trigger: 'blur' }],
        password: [{ min: 6, max: 12, message: '请输入6至12位之间的密码', trigger: 'blur' }],
        mobile: [{ required: true, validator: validatePhone, trigger: 'blur' }]
      },
      redactFormVisible: false,
      //编辑表单
      redactForm: { username: '', realname: '', email: '', auth_group_id: '', vip_id: '', mobile: undefined, password: undefined, assist_id: '', platter_id: [] },
      redactRules: {
        username: [{ required: true, trigger: "blur", message: "请输入用户名" }],
        email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
        password: [{ min: 6, max: 12, message: '请输入6至12位之间的密码', trigger: 'blur' }],
        mobile: [{ required: true, validator: validatePhone, trigger: 'blur' }]
      },
      redactType: "password",
      //vip下拉
      vipMenu: [],
      //所属组别下拉
      authMenu: [],
      listQuery: { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), username: undefined, mobile: undefined, sort: '', gId: undefined, vId: undefined },
      //删除弹窗
      deleteDialogs: { show: false, deleteText: '', deleteId: 0 },
      searchShow: false,
      platterOptions:[]
    }
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
    this.getqueryAdmin()
    this.getqueryVipName()
    this.getqueryAuthGroup()
    this.getPlatterControl()
  },
  methods: {
    //导出用户信息
    getexportAuthAdmin() {
      exportAuthAdmin({ userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip") }).then(({ data }) => {
        window.open('https://' + data.url)
      }).catch(err => {
        console.log('失败', err)
      })
    },
    searchShows() {
      this.searchShow = !this.searchShow
    },
    getPlatterControl() {
      getPlatter({userId: localStorage.getItem("ID")}).then(res => {
        this.platterOptions = res.data
      }).catch(err => {
      })
    },
    //表格排序事件
    tableSortCge(column) {
      let order = ''
      column.order == "descending" ? order = 'desc' : order = 'asc'
      // if (column.prop == 'status') {
      //   column.order == "descending" ? order = 2 : order = 1
      // }
      let sort = [{ field: column.prop, sort: order }]
      this.listQuery.sort = JSON.stringify(sort)
      console.log('排序参数', this.listQuery.sort)
      this.getqueryAdmin()
    },
    //删除
    getdeleteAuthAdmin(id) {
      this.deleteDialogs.show = true
      this.deleteDialogs.deleteId = id
    },
    //删除按钮事件
    deleteEvents() {
      let params = { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), id: this.deleteDialogs.deleteId }
      deleteAuthAdmin(params).then(res => {
        this.$message.success(res.msg)
        this.getqueryAdmin()
      })
    },
    redactshowPwd(type) {
      if (this.redactType === "password") {
        this.redactType = "";
      } else {
        this.redactType = "password";
      }
      this.$nextTick(() => {
        this.$refs.redactPassword.focus();
      })
    },
    //禁用或启用用户
    getenableAuthAdmin(row) {
      let status = row.status == 1 ? '禁用' : '启用'
      this.$confirm(`将该用户${status}, 是否继续?`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        let data = { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), id: row.id, status: row.status == 1 ? 2 : 1 }
        enableAuthAdmin(data).then(res => {
          this.$message({ type: 'success', message: res.msg })
          this.getqueryAdmin()
        })
      }).catch(() => { });
    },
    //添加子账户
    getsonRegister(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.userId = localStorage.getItem("ID")
          addForm.last_ip = sessionStorage.getItem("Ip")
          sonRegister(addForm).then(res => {
            this.$message.success(res.msg)
            this.getqueryAdmin()
            this.dialogFormVisible = false
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    getqueryAdmin() {
      queryAdmin(this.listQuery).then(res => {
        this.browserTable = res.data
        this.total = res.total
      }).catch(err => {
        this.browserTable = []
        this.total = 0
      })
    },
    //编辑账号信息
    updateAuthAdmin(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let redactForm = JSON.parse(JSON.stringify(this.redactForm))
          redactForm.last_ip = sessionStorage.getItem("Ip")
          redactForm.userId = localStorage.getItem("ID")
          redactForm.id = this.subjectId
          redactForm.email == '' ? delete redactForm.email : redactForm.email
          redactForm.realname == '' ? delete redactForm.realname : redactForm.realname
          updateAuthAdmin(redactForm).then(res => {
            this.redactFormVisible = false
            this.$message.success(res.msg)
            this.getqueryAdmin()
          }).catch(err => {})
        } else {
          return false
        }
      })
    },
    //根据ID查询账号信息
    async getqueryIdAuthAdmin(id) {
      this.subjectId = id
      await queryIdAuthAdmin({ userId: id }).then(res => {
        this.redactFormVisible = true
        let data = res.data
        Object.keys(this.redactForm).forEach(key => { this.redactForm[key] = data[key] })
        this.redactForm.vip_id = data.name
        this.redactForm.auth_group_id = data.title
        //一开始返回的是等级ID，回显处理操作
        // let vip = ''
        // let auth = ''
        //if (!(this.vipMenu instanceof Array)) { this.vipMenu = [this.vipMenu] }
        // this.vipMenu.forEach(item => { if (item.id == data.vip_id) { vip = item.name } })
        // this.authMenu.forEach(item => { if (item.id == data.auth_group_id) { auth = item.title } })
      })

    },
    //获取vip列表
    async getqueryVipName() {
      await queryVipName({ userId: localStorage.getItem("ID") }).then(res => { this.vipMenu = res.data }).catch(err => { this.vipMenu = [] })
    },
    //获取权限列表
    getqueryAuthGroup() {
      queryAuthGroup({ userId: localStorage.getItem("ID") }).then(res => { this.authMenu = res.data }).catch(err => { this.authMenu = [] })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getqueryAdmin();
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getqueryAdmin();
    },
    //搜索,1:用户名查询，2手机号查询
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.type = 2
          this.listQuery.username = this.searchTable
          this.getqueryAdmin();
          break;
        case '2':
          this.listQuery.type = 3
          this.listQuery.mobile = this.searchTable
          this.getqueryAdmin();
          break;
      }
    },
    //复杂查询重置
    restParams() {
      this.listQuery = { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), username: undefined, mobile: undefined, sort: '', gId: undefined, vId: undefined }
    },
    Refresh() {
      this.listQuery = { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), username: undefined, mobile: undefined, sort: '', gId: undefined, vId: undefined }
      this.getqueryAdmin()
    },
    //编辑添加表单关闭事件
    redactFormclose() {
      this.$nextTick(() => {
        this.$refs.redactRuleForm.resetFields();
        this.redactForm = { username: '', realname: '', email: '', auth_group_id: '', vip_id: '', mobile: undefined, password: undefined, assist_id: '', platter_id: []}
      })
    },
    addFormclose() {
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
      })
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.show-pwd {
  position: absolute;
  right: 15px;
  top: 2px;
  font-size: 16px;
  cursor: pointer;
  user-select: none;
}
</style>
